package actor.remote.identity

import actor.remote.url.Messages._
import akka.actor._
import akka.util.Timeout

import scala.concurrent.duration._
import akka.pattern._
import com.typesafe.config.ConfigFactory

/**
 *  根据 Identify 来查找remote
 */
object LocalSelectionDemo extends App {


  val localSystem = ActorSystem("localSystem")
  import localSystem.dispatcher

  val path = "akka.tcp://remoteSystem@127.0.0.1:2552/user/supervisorActor/calculator"


  implicit val timeout = Timeout(5 seconds)
  for (calcActor : ActorRef <- localSystem.actorSelection(path).resolveOne()) {
    calcActor ! Clear
    calcActor ! Num(13.0)
    calcActor ! Mul(1.5)
    ((calcActor ? GetResult).mapTo[String]) foreach println
    calcActor ! Div(0.0)
    calcActor ! Div(1.5)
    calcActor ! Add(100.0)
    ((calcActor ? GetResult).mapTo[String]) foreach println
  }
  scala.io.StdIn.readLine()
  localSystem.terminate()
}
object LocalIdentifyDemo extends App {
  class RemoteCalc extends Actor with ActorLogging {
    val path = "akka.tcp://remoteSystem@127.0.0.1:2552/user/supervisorActor/calculator"
    context.actorSelection(path) ! Identify(path)  //semd req for ActorRef
    import context.dispatcher
    implicit val timeout = Timeout(5 seconds)
    override def receive: Receive = {
      case ActorIdentity(p,someRef) if p.equals(path) =>
        someRef foreach { calcActor =>

          calcActor ! Clear
          calcActor ! Num(13.0)
          calcActor ! Mul(1.5)
          ((calcActor ? GetResult).mapTo[String]) foreach println

          calcActor ! Div(0.0)
          calcActor ! Div(1.5)
          calcActor ! Add(100.0)
          ((calcActor ? GetResult).mapTo[String]) foreach println

        }
    }

  }

  val localSystem = ActorSystem("localSystem",ConfigFactory.load("local"))
  val localActor = localSystem.actorOf(Props[RemoteCalc],"localActor")

  scala.io.StdIn.readLine()
  localSystem.terminate()

}
